defmodule Iocp.Dumper do
  @moduledoc false

  use GenServer

  def start_link(path) do
    GenServer.start_link(__MODULE__, path, name: __MODULE__)
  end

  def dump(address, payload) when is_list(payload) do
    GenServer.call(__MODULE__, {:dump, {address, payload}})
  end

  @impl true
  def init(path) do
    {:ok, file} = File.open(path, [:append])
    Process.link(file)
    {:ok, file}
  end

  @impl true
  def handle_call({:dump, {address, payload}}, _from, file) when is_list(payload) do
    record = [{:address, address} | payload]
             |> Stream.map(fn{k, v}-> "#{k}=#{v}" end)
             |> Enum.join("\t")
    IO.puts(file, record)
    {:reply, :ok, file}
  end

  @impl true
  def terminate(_reason, file) do
    File.close(file)
  end
end
